package com.anpy.security.controller;

import com.anpy.security.entity.Role;
import com.anpy.security.entity.User;
import com.anpy.security.security.PlatformContextHolder;
import com.anpy.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;
    
    // 不需要RoleService，我们已经在UserService中实现了相关功能

    /**
     * Get all users for the current platform
     * Requires ADMIN role in the current platform
     */
    @GetMapping
//    @PreAuthorize("hasPlatformRole('ADMIN')")
    public ResponseEntity<List<User>> getAllUsers() {
        try {
            String platformCode = PlatformContextHolder.getPlatformCode();
            // 如果platformCode为空，设置默认值
            if (platformCode == null || platformCode.isEmpty()) {
                // 可以从配置中获取默认平台代码
                platformCode = "devOps"; // 设置一个默认平台代码
            }
            List<User> users = userService.getAllUsersByPlatform(platformCode);
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            // 记录异常信息
            e.printStackTrace();
            // 返回空列表而不是错误
            return ResponseEntity.ok(java.util.Collections.emptyList());
        }
    }

    /**
     * Get user by ID
     * Requires either ADMIN role or USER_READ permission in the current platform
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasPlatformRole('ADMIN') or hasPlatformPermission('USER_READ')")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        User user = userService.getUserById(id, platformCode);
        return ResponseEntity.ok(user);
    }

    /**
     * Create a new user
     * Requires ADMIN role in the current platform
     */
    @PostMapping
    @PreAuthorize("hasPlatformRole('ADMIN')")
    public ResponseEntity<User> createUser(@RequestBody User user) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        User createdUser = userService.createUser(user, platformCode);
        return ResponseEntity.ok(createdUser);
    }

    /**
     * Update an existing user
     * Requires ADMIN role in the current platform
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasPlatformRole('ADMIN')")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        User updatedUser = userService.updateUser(id, user, platformCode);
        return ResponseEntity.ok(updatedUser);
    }

    /**
     * Delete a user
     * Requires ADMIN role in the current platform
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasPlatformRole('ADMIN')")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        userService.deleteUser(id, platformCode);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 获取用户的所有角色
     * 需要当前平台的ADMIN角色或USER_READ权限
     */
    @GetMapping("/{id}/roles")
    @PreAuthorize("hasPlatformRole('ADMIN') or hasPlatformPermission('USER_READ')")
    public ResponseEntity<List<Role>> getUserRoles(@PathVariable Long id) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        List<Role> roles = userService.getUserRoles(id, platformCode);
        return ResponseEntity.ok(roles);
    }
    
    /**
     * 为用户分配角色
     * 需要当前平台的ADMIN角色
     */
    @PostMapping("/{userId}/roles/{roleId}")
//    @PreAuthorize("hasPlatformRole('ADMIN')")
    public ResponseEntity<User> assignRoleToUser(
            @PathVariable Long userId,
            @PathVariable Long roleId) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        User updatedUser = userService.assignRoleToUser(userId, roleId, platformCode);
        return ResponseEntity.ok(updatedUser);
    }
    
    /**
     * 移除用户的角色
     * 需要当前平台的ADMIN角色
     */
    @DeleteMapping("/{userId}/roles/{roleId}")
    @PreAuthorize("hasPlatformRole('ADMIN')")
    public ResponseEntity<User> removeRoleFromUser(
            @PathVariable Long userId,
            @PathVariable Long roleId) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        User updatedUser = userService.removeRoleFromUser(userId, roleId, platformCode);
        return ResponseEntity.ok(updatedUser);
    }
    
    /**
     * 批量更新用户角色
     * 需要当前平台的ADMIN角色
     */
    @PutMapping("/{userId}/roles")
    @PreAuthorize("hasPlatformRole('ADMIN')")
    public ResponseEntity<User> updateUserRoles(
            @PathVariable Long userId,
            @RequestBody List<Long> roleIds) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        User updatedUser = userService.updateUserRoles(userId, roleIds, platformCode);
        return ResponseEntity.ok(updatedUser);
    }
}
